<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-select
        v-model="listQuery.shopName"
        clearable
        style="width: 200px"
        class="filter-item"
        placeholder="请选择项目"
        @change="selectProductType1"
      >
        <el-option v-for="(item,index) in shopList" :key="index" :label="item.shopName" :value="{ value: item.id, label: item.shopName}" />
      </el-select>
      <el-select
        v-model="listQuery.jiedianName"
        clearable
        style="width: 200px"
        class="filter-item"
        placeholder="请选择节点"
        @change="selectProductType2"
      >
        <el-option v-for="(item,index) in jiedianList" :key="index" :label="item.title" :value="{ value: item.id, label: item.title}" />
      </el-select>
      <el-input v-model="listQuery.title" clearable class="filter-item" style="width: 200px;" placeholder="文件名称" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button
        v-permission="['admin:file:create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >新增</el-button>
      <!--      <el-button
        v-permission="['admin:file:batchdelete']"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        @click="handleBatchDelete"
      >批量删除</el-button>-->

    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      style="white-space: pre-line"
      @selection-change="handleSelectionChange"
    >

      <el-table-column align="center" type="selection" width="55" />
      <el-table-column prop="name" align="center" label="文件">
        <template slot-scope="scope"><el-col>
        <a :href="scope.row.url" target="_blank">{{ scope.row.name }}</a></el-col>
        </template>

      </el-table-column>
      <el-table-column prop="shopName" align="center" label="所属项目"/>
      <el-table-column prop="jiedianName" align="center" label="所属节点"/>
      <el-table-column align="center" label="完成时间" prop="finishTime">
        <template slot-scope="scope"><el-col>{{ scope.row.gmtCreate | formatGmt }}</el-col></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-permission="['admin:file:update']"
            type="primary"
            size="mini"
            @click="handleDown(scope.row)"
          >下载</el-button>

          <!--          <el-button
                      v-permission="['admin:file:update']"
                      type="primary"
                      size="mini"
                      @click="handleUpdate(scope.row)"
                    >编辑</el-button>
                    --><el-button
          v-permission="['admin:file:delete']"
          type="danger"
          size="mini"
          @click="handleDelete(scope.row)"
        >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="" prop="id" style="display: none">
          <el-input v-model="dataForm.id" disabled />
        </el-form-item>

        <el-form-item label="项目" prop="shopId">
          <el-select
            v-model="dataForm.shopName"
            clearable
            style="width: 200px"
            class="filter-item"
            placeholder="请选择项目"
            @change="selectProductType3"
          >
            <el-option v-for="(item,index) in shopList" :key="index" :label="item.shopName" :value="{ value: item.id, label: item.shopName}" />
          </el-select>

        </el-form-item>
        <el-form-item label="节点" prop="jiedianId">

          <el-select
            v-model="dataForm.jiedian"
            clearable
            style="width: 200px"
            class="filter-item"
            placeholder="请选择节点"
            @change="selectProductType4"
          >
            <el-option v-for="(item,index) in jiedianList" :key="index" :label="item.title" :value="{ value: item.id, label: item.title}" />
          </el-select>
        </el-form-item>
        <el-form-item label="文件">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :limit="5"
            :file-list="fileList"
            :on-success="handleFileUrl"
            :on-remove="handleFileRemove"
            multiple
            accept=".jpg, .jpeg, .png, .gif, .doc, .docx, .xls, .xlsx, .zip, .rar"
            list-type="picture-card"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus==='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.el-table .cell {
  white-space: pre-line;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<script>
import { list, create, del, update, active, batchDelete } from '@/api/shopFile'
import { searchGoods } from '@/api/goods'
import { uploadPath, uploadExcelPath } from '@/api/storage'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { selectShop } from '@/api/frontutil'
import { getToken } from '@/utils/auth'

export default {
  name: 'ShopMoney',
  components: { Pagination },
  filters: {
  },
  data() {
    return {
      uploadPath,
      uploadExcelPath,
      fileList: [],
      shopList: [],
      jiedianList: [],
      statusMap: [{ value: 0, name: '未完成' }, { value: 1, name: '完成' }],
      list: undefined,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        limit: 20,
        shopId: this.$route.query.shopId,
        shopName: this.$route.query.shopName
      },
      options: [],
      dataForm: {
        id: undefined,
        shopId: this.$route.query.shopId,
        shopName: this.$route.query.shopName,
        jiedianId: undefined,
        fileList: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建',
        upload: '上传'
      },
      rules: {},
      selectedIds: []
    }
  },
  computed: {

    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  created() {
    this.listShop()
    this.getJiedianList()
    this.getList()
  },
  methods: {
    listShop() {
      selectShop()
        .then(response => {
          this.shopList = response.data.data
        })
        .catch(() => {
        })
    },

    selectProductType1(data) {
      const { value, label } = data
      this.listQuery.shopName = label
      this.listQuery.shopId = value
    },
    selectProductType2(data) {
      const { value, label } = data
      this.listQuery.jiedianName = label
      this.listQuery.jiedianId = value
    },
    selectProductType3(data) {
      const { value, label } = data
      this.dataForm.shopName = label
      this.dataForm.shopId = value
    },
    selectProductType4(data) {
      const { value, label } = data
      this.dataForm.jiedianName = label
      this.dataForm.jiedianId = value
    },
    getJiedianList() {
      searchGoods(null, 2, null)
        .then(response => {
          this.jiedianList = response.data.data
        })
        .catch(() => {
        })
    },
    getList() {
      this.listLoading = true
      list(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    empty() {
      this.listQuery.title = ''
    },
    resetForm() {
      this.fileList = []
      this.dataForm = {
        id: undefined,
        fileList: [],
        shopId: this.$route.query.shopId,
        shopName: this.$route.query.shopName

      }
    },

    handleStatus(row) {
      this.resetForm()
      this.dataForm.id = row.id
      this.dataForm.status = row.status === 1 ? 0 : 1
      active(this.dataForm)
        .then(res => {
          this.$notify.success({
            title: '成功',
            message: '状态更改成功'
          })
          this.getList()
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleDown(row) {
      window.open(row.url)
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      create(this.dataForm)
        .then(response => {
          this.getList()
          this.dialogFormVisible = false
          this.$notify.success({
            title: '成功',
            message: '创建成功'
          })
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      update(this.dataForm)
        .then(response => {
          this.getList()
          this.dialogFormVisible = false
          this.$notify.success({
            title: '成功',
            message: '更新成功'
          })
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: '失败'
            })
          })
      }).catch(() => {
        return false
      })
    },
    handleSelectionChange(e) {
      this.selectedIds = []
      e.forEach(item => {
        this.selectedIds.push(item.id)
      })
    },
    handleFileUrl(response, file, fileList) {
      if (response.errno === 200) {
        this.dataForm.fileList.push(
          {
            name: file.name,
            url: response.url
          }
        )
        this.fileList.push({
          name: file.name,
          url: this.getPreviwImg(file.name)
        })
      }
    },
    handleFileRemove: function(file, fileList) {
      for (var i = 0; i < this.goods.fileList.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.url
        }

        if (this.dataForm.fileList[i] === url) {
          this.dataForm.fileList.splice(i, 1)
        }
      }
    },
    handleBatchDelete(e) {
      if (this.selectedIds.length === 0) return
      // 执行批量删除
      this.$confirm('此操作将永久删除选中的' + this.selectedIds.length + '条新闻, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchDelete(this.selectedIds).then(() => {
          this.getList()
        })
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    getImgUrl(image) {
      return require(`@/assets/file/${image}`)
    },
    getPreviwImg(filename) {
      filename = filename
        .substring(filename.lastIndexOf('.'))
        .toLowerCase()
        .split('.')[1]
      const imageObject = {
        png: 'png.png',
        jpg: 'png.png',
        jpeg: 'png.png',
        gif: 'png.png',
        doc: 'doc.png',
        docx: 'doc.png',
        xls: 'xls.png',
        xlsx: 'xls.png',
        pdf: 'pdf.png',
        zip: 'zip.png',
        '7z': 'zip.png',
        rar: 'zip.png',
        txt: 'file.png'
      }
      return this.getImgUrl(imageObject[filename])
    }
  }
}
</script>

